/**
 * 配置Schema管理工具
 * 提供Schema的注册、获取、验证等功能
 */

import type { ConfigSchema, FieldSchema, ValidationRule } from '@/types/schema'

// === 字段类型定义 ===
export type FieldType = 
  | 'string' 
  | 'number' 
  | 'boolean' 
  | 'select' 
  | 'multiSelect'
  | 'array' 
  | 'object' 
  | 'json'
  | 'textarea'
  | 'color'
  | 'file'
  | 'date'
  | 'range'
  | 'tags'
  | 'skillSelector'
  | 'attributeEditor'
  | 'qualityRange'
  | 'emoji'

// === 内置配置Schema定义 ===
export const EquipmentConfigSchema: ConfigSchema = {
  version: "1.0.0",
  type: "equipment",
  name: "装备配置",
  description: "游戏装备模板配置",
  fields: [
    {
      key: "id",
      label: "装备ID",
      type: "string",
      required: true,
      description: "装备的唯一标识符",
      placeholder: "输入唯一的装备ID",
      rules: [
        { type: "required", message: "装备ID不能为空" },
        { type: "pattern", value: "^[a-zA-Z0-9_-]+$", message: "ID只能包含字母、数字、下划线和连字符" }
      ],
      group: "basic",
      order: 1
    },
    {
      key: "name",
      label: "装备名称",
      type: "string",
      required: true,
      placeholder: "输入装备名称",
      group: "basic",
      order: 2
    },
    {
      key: "emoji",
      label: "表情符号",
      type: "emoji",
      defaultValue: "⚔️",
      description: "装备的表情符号图标",
      group: "basic",
      order: 3
    },
    {
      key: "sys",
      label: "体系",
      type: "select",
      required: true,
      options: [
        { label: "现代", value: "现代" },
        { label: "古典", value: "古典" },
        { label: "未来", value: "未来" }
      ],
      group: "basic",
      order: 4
    },
    {
      key: "type",
      label: "类型",
      type: "select",
      required: true,
      options: [
        { label: "武器", value: "武器" },
        { label: "防具", value: "防具" },
        { label: "饰品", value: "饰品" }
      ],
      group: "basic",
      order: 5
    },
    {
      key: "job",
      label: "职业",
      type: "select",
      required: true,
      options: [
        { label: "血骑士", value: "血骑士" },
        { label: "圣牧师", value: "圣牧师" },
        { label: "影刺客", value: "影刺客" },
        { label: "通用", value: "通用" }
      ],
      group: "basic",
      order: 6
    },
    {
      key: "solt",
      label: "装备部位",
      type: "select",
      required: true,
      options: [
        { label: "主手", value: "主手" },
        { label: "副手", value: "副手" },
        { label: "头部", value: "头部" },
        { label: "胸部", value: "胸部" },
        { label: "腿部", value: "腿部" },
        { label: "脚部", value: "脚部" },
        { label: "手部", value: "手部" },
        { label: "戒指", value: "戒指" },
        { label: "项链", value: "项链" }
      ],
      group: "basic",
      order: 7
    },
    {
      key: "desc",
      label: "描述",
      type: "textarea",
      placeholder: "输入装备描述",
      group: "basic",
      order: 8
    },
    {
      key: "quality",
      label: "品质范围",
      type: "range",
      defaultValue: { min: 1, max: 5 },
      description: "装备的品质等级范围",
      group: "quality",
      order: 10
    },
    {
      key: "enabled",
      label: "启用状态",
      type: "boolean",
      defaultValue: true,
      group: "metadata",
      order: 40
    },
    {
      key: "tags",
      label: "标签",
      type: "tags",
      defaultValue: [],
      description: "用于分类和搜索的标签",
      group: "metadata",
      order: 41
    }
  ],
  groups: [
    { key: "basic", label: "基础信息", icon: "info", order: 1 },
    { key: "quality", label: "品质配置", icon: "star", order: 2 },
    { key: "metadata", label: "元数据", icon: "tag", order: 5 }
  ],
  actions: {
    create: true,
    edit: true,
    delete: true,
    duplicate: true,
    export: true,
    import: true
  },
  listConfig: {
    primaryField: "name",
    secondaryFields: ["job", "type", "sys"],
    statusField: "enabled",
    searchFields: ["name", "id", "desc"],
    sortFields: ["name", "job", "type", "lastModified"]
  },
  previewConfig: {
    template: "equipment-preview",
    fields: ["name", "emoji", "desc", "quality"]
  }
}

export const SkillConfigSchema: ConfigSchema = {
  version: "1.0.0",
  type: "skill",
  name: "技能配置",
  description: "游戏技能配置",
  fields: [
    {
      key: "skillId",
      label: "技能ID",
      type: "string",
      required: true,
      placeholder: "输入唯一的技能ID",
      group: "basic",
      order: 1
    },
    {
      key: "name",
      label: "技能名称",
      type: "string",
      required: true,
      placeholder: "输入技能名称",
      group: "basic",
      order: 2
    },
    {
      key: "description",
      label: "技能描述",
      type: "textarea",
      placeholder: "输入技能描述",
      group: "basic",
      order: 3
    },
    {
      key: "type",
      label: "技能类型",
      type: "select",
      options: [
        { label: "主动技能", value: "active" },
        { label: "被动技能", value: "passive" },
        { label: "光环技能", value: "aura" }
      ],
      group: "basic",
      order: 4
    },
    {
      key: "quality",
      label: "技能品质",
      type: "select",
      options: [
        { label: "普通", value: 1 },
        { label: "优秀", value: 2 },
        { label: "稀有", value: 3 },
        { label: "史诗", value: 4 },
        { label: "传说", value: 5 }
      ],
      group: "basic",
      order: 5
    },
    {
      key: "cooldown",
      label: "冷却时间",
      type: "number",
      min: 0,
      defaultValue: 0,
      description: "技能冷却回合数",
      group: "mechanics",
      order: 10
    },
    {
      key: "maxLevel",
      label: "最高等级",
      type: "number",
      min: 1,
      max: 20,
      defaultValue: 1,
      group: "mechanics",
      order: 11
    },
    {
      key: "enabled",
      label: "启用状态",
      type: "boolean",
      defaultValue: true,
      group: "metadata",
      order: 40
    }
  ],
  groups: [
    { key: "basic", label: "基础信息", order: 1 },
    { key: "mechanics", label: "技能机制", order: 2 },
    { key: "metadata", label: "元数据", order: 3 }
  ],
  actions: {
    create: true,
    edit: true,
    delete: true,
    duplicate: true,
    export: true
  },
  listConfig: {
    primaryField: "name",
    secondaryFields: ["type", "quality"],
    statusField: "enabled",
    searchFields: ["name", "skillId", "description"],
    sortFields: ["name", "type", "quality"]
  }
}

// 其他配置Schema
export const PropConfigSchema: ConfigSchema = {
  version: "1.0.0",
  type: "prop",
  name: "道具配置",
  description: "游戏道具配置",
  fields: [
    {
      key: "id",
      label: "道具ID",
      type: "string",
      required: true,
      group: "basic",
      order: 1
    },
    {
      key: "name",
      label: "道具名称",
      type: "string",
      required: true,
      group: "basic",
      order: 2
    },
    {
      key: "type",
      label: "道具类型",
      type: "select",
      options: [
        { label: "消耗品", value: "consumable" },
        { label: "材料", value: "material" },
        { label: "任务物品", value: "quest" }
      ],
      group: "basic",
      order: 3
    },
    {
      key: "stackable",
      label: "可堆叠",
      type: "boolean",
      defaultValue: true,
      group: "basic",
      order: 4
    },
    {
      key: "maxStack",
      label: "最大堆叠数",
      type: "number",
      min: 1,
      defaultValue: 99,
      showWhen: [{ field: "stackable", operator: "==", value: true }],
      group: "basic",
      order: 5
    }
  ],
  groups: [
    { key: "basic", label: "基础信息", order: 1 }
  ],
  listConfig: {
    primaryField: "name",
    secondaryFields: ["type"],
    searchFields: ["name", "id"],
    sortFields: ["name", "type"]
  }
}

// === Schema管理器 ===
export class ConfigSchemaManager {
  private schemas = new Map<string, ConfigSchema>()
  
  constructor() {
    // 注册内置schema
    this.registerSchema(EquipmentConfigSchema)
    this.registerSchema(SkillConfigSchema)
    this.registerSchema(PropConfigSchema)
  }
  
  /**
   * 注册配置Schema
   */
  registerSchema(schema: ConfigSchema): void {
    this.schemas.set(schema.type, schema)
  }
  
  /**
   * 获取配置Schema
   */
  getSchema(type: string): ConfigSchema | undefined {
    return this.schemas.get(type)
  }
  
  /**
   * 获取所有注册的Schema
   */
  getAllSchemas(): ConfigSchema[] {
    return Array.from(this.schemas.values())
  }
  
  /**
   * 获取Schema类型列表
   */
  getSchemaTypes(): string[] {
    return Array.from(this.schemas.keys())
  }
  
  /**
   * 验证配置数据是否符合Schema
   */
  validateData(type: string, data: any): { valid: boolean, errors: string[] } {
    const schema = this.getSchema(type)
    if (!schema) {
      return { valid: false, errors: [`未找到类型 ${type} 的Schema`] }
    }
    
    const errors: string[] = []
    
    // 验证必填字段
    for (const field of schema.fields) {
      if (field.required && (data[field.key] === undefined || data[field.key] === null || data[field.key] === '')) {
        errors.push(`字段 ${field.label} 不能为空`)
      }
      
      // 验证字段规则
      if (field.rules && data[field.key] !== undefined) {
        for (const rule of field.rules) {
          const fieldValue = data[field.key]
          
          switch (rule.type) {
            case 'pattern':
              if (typeof fieldValue === 'string' && rule.value) {
                const regex = new RegExp(rule.value)
                if (!regex.test(fieldValue)) {
                  errors.push(rule.message)
                }
              }
              break
            case 'min':
              if (typeof fieldValue === 'number' && fieldValue < rule.value) {
                errors.push(rule.message)
              }
              break
            case 'max':
              if (typeof fieldValue === 'number' && fieldValue > rule.value) {
                errors.push(rule.message)
              }
              break
          }
        }
      }
    }
    
    return { valid: errors.length === 0, errors }
  }
  
  /**
   * 从现有配置数据推断Schema（实验性功能）
   */
  inferSchemaFromData(type: string, data: any[]): ConfigSchema {
    if (data.length === 0) {
      throw new Error('无法从空数据推断Schema')
    }
    
    const fields: FieldSchema[] = []
    const sampleData = data[0]
    
    // 分析每个字段
    for (const [key, value] of Object.entries(sampleData)) {
      const field: FieldSchema = {
        key,
        label: this.prettifyFieldName(key),
        type: this.inferFieldType(value),
        order: fields.length + 1
      }
      
      // 分析是否为必填字段
      const hasValue = data.every(item => item[key] !== undefined && item[key] !== null && item[key] !== '')
      if (hasValue) {
        field.required = true
      }
      
      // 如果是选择类型，提取选项
      if (field.type === 'select') {
        const uniqueValues = [...new Set(data.map(item => item[key]))]
        field.options = uniqueValues.map(value => ({
          label: String(value),
          value: value
        }))
      }
      
      fields.push(field)
    }
    
    return {
      version: "1.0.0",
      type,
      name: this.prettifyFieldName(type),
      description: `自动生成的${this.prettifyFieldName(type)}配置`,
      fields,
      actions: {
        create: true,
        edit: true,
        delete: true,
        duplicate: true,
        export: true
      },
      listConfig: {
        primaryField: fields[0]?.key || 'name',
        secondaryFields: fields.slice(1, 3).map(f => f.key),
        searchFields: fields.filter(f => f.type === 'string').map(f => f.key),
        sortFields: fields.map(f => f.key)
      }
    }
  }
  
  /**
   * 推断字段类型
   */
  private inferFieldType(value: any): FieldType {
    if (value === null || value === undefined) return 'string'
    
    switch (typeof value) {
      case 'boolean':
        return 'boolean'
      case 'number':
        return 'number'
      case 'string':
        // 如果字符串很长，使用textarea
        if (value.length > 50 || value.includes('\n')) {
          return 'textarea'
        }
        // 如果看起来像选项值，使用select
        if (value.length < 20 && !/\s/.test(value)) {
          return 'select'
        }
        return 'string'
      case 'object':
        if (Array.isArray(value)) {
          return 'array'
        }
        return 'object'
      default:
        return 'string'
    }
  }
  
  /**
   * 美化字段名称
   */
  private prettifyFieldName(key: string): string {
    // 将驼峰命名转换为中文友好的名称
    const nameMap: Record<string, string> = {
      'id': 'ID',
      'name': '名称',
      'type': '类型',
      'description': '描述',
      'enabled': '启用状态',
      'quality': '品质',
      'sys': '体系',
      'job': '职业',
      'solt': '部位',
      'skillId': '技能ID',
      'maxLevel': '最高等级',
      'cooldown': '冷却时间'
    }
    
    return nameMap[key] || key.replace(/([A-Z])/g, ' $1').trim()
  }
}

// 导出全局Schema管理器实例
export const schemaManager = new ConfigSchemaManager()

// 导出类型定义
export type { ConfigSchema, FieldSchema, ValidationRule } from '@/types/schema'
